package com.jhf.youke.order.domain.model.Do;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.jhf.youke.core.ddd.BaseDoEntity;
import com.jhf.youke.core.entity.Message;
import com.jhf.youke.core.entity.User;
import com.jhf.youke.core.utils.IdGen;
import com.jhf.youke.core.utils.StringUtils;
import com.jhf.youke.order.domain.exception.OrderException;
import com.jhf.youke.order.domain.model.dto.CustomerDto;
import com.jhf.youke.order.domain.model.po.OrderPo;
import lombok.Data;

import java.math.BigDecimal;
import java.util.*;


/**
 * @author RHJ
 */
@Data
public class OrderDo extends BaseDoEntity {

    private static final long serialVersionUID = -99191807894672647L;

    /** 编码 **/
    private String code;

    /** 名字 **/
    private String name;

    /** 类型 **/
    private Integer type;

    /** 用户标识 **/
    private Long customerId;

    /** 客户标识 **/
    private String customerName;

    /** 单位标识 **/
    private Long companyId;

    /** 单位名 **/
    private String companyName;

    /** 总金额 **/
    private BigDecimal sumFee;

    /** 实际金额 **/
    private BigDecimal fee;

    /** 优惠金额 **/
    private BigDecimal couponFee;

    /** 状态 **/
    private Integer status;

    /** 支付状态 **/
    private Integer payStatus;

    /** 支付时间 **/
    private Date payTime;

    /** 完成时间 **/
    private Date finishTime;

    /** 团长ID **/
    private Long salesman;

    /** 团长名 **/
    private String salesmanName;

    /** 团长支付状态 **/
    private Integer salesPayStatus;

    private String phone;
    /**  收货人 **/
    private String consignee;
    /**  收货地址 **/
    private String receiveAddress;
    /** 经度 **/
    private String longitude;
    /** 纬度 **/
    private String latitude;

    private CustomerDto customer;

    private List<OrderListDo> itemList;

    public OrderDo(){
       super();
    }

    public OrderDo(Long salesman){
      super();
      this.salesman = salesman;
    }

    public OrderDo(Map<String,Object> productRelease, User user){
        super();
        BigDecimal price = new BigDecimal(StringUtils.chgNull(productRelease.get("price")));
        this.code = IdGen.id().toString();
        this.companyId = user.getRootId();
        this.companyName = user.getCompanyName();
        this.customerId = user.getId();
        this.customerName = user.getName();
        this.fee = price;
        this.sumFee = price;
        this.payStatus = 1;
        this.status = 101;
    }

    public <T> T requireNonNull(T obj, Object column, String errorMessage) {
        if (Objects.isNull(column)) {
            throw new OrderException(errorMessage);
        }
        return obj;
    }

    public void validateVideoAgainPay(Optional<OrderPo> orderPo){
        if(orderPo.get() == null){
            throw new OrderException("订单不存在");
        }
        int paySuccess = 3;
        if(orderPo.get().getPayStatus() == paySuccess){
            throw new OrderException("订单已支付");
        }
    }

    public void validateVideoAgainPay(List<OrderPo> orderPoList){
        if(orderPoList.size() > 0){
            throw new OrderException("已购买此商品，无需重复购买");
        }
    }

    private OrderDo validateNull(OrderDo orderDo){
          // 可使用链式法则进行为空检查
          orderDo.
          requireNonNull(orderDo, orderDo.getRemark(),"不能为NULL");

        return orderDo;
    }

    /**  订单金额计算 **/
    public OrderDo computeFee(){
      if(this.itemList != null){
        BigDecimal fee = BigDecimal.ZERO;
        for(OrderListDo item : this.itemList){
           BigDecimal itemFee = item.getNum().multiply(item.getPrice());
           item.setFee(itemFee);
           fee = fee.add(itemFee);
        }
        this.fee = fee;
        this.sumFee = fee;
      }
      return this;
    }

    public OrderDo completed(){
      this.status = 104;
      this.finishTime = DateUtil.date();
      return this;
    }

    /**  订单确认，所有人支付完成进行确认 **/
    public OrderDo confirm(){
      this.status = 102;
      return this;
    }

    public OrderDo deliverGoods(){
      this.status = 103;
      return this;
    }

    public OrderDo termination(){
      this.status = 105;
      return this;
    }

    /**  订单支付 **/
    public OrderDo paid(){
      this.payStatus = 3;
      this.payTime = DateUtil.date();
      return this;
    }


    /**  视频订单支付 **/
    public OrderDo videoPaid(List<OrderPo> list){
        if(list.size() == 0){
            throw new OrderException("订单不存在");
        }
        int paySuccess = 3;
        if(list.get(0).getPayStatus() == paySuccess){
            throw new OrderException("订单已支付");
        }
        this.id = list.get(0).getId();
        this.payStatus = 3;
        this.status = 105;
        this.payTime = DateUtil.date();
        return this;
    }


    public String sendCustomerMsg(){
      Message message = new Message();
      message.setTopic("createCustomerConsume");
      message.setTag("all");
      message.setMessages(JSONUtil.toJsonStr(this.customer));
      return JSONUtil.toJsonStr(message);
    }


  public String sendCommissionMsg() {
      Message message = new Message();
      message.setTopic("createCommissionConsume");
      message.setTag("all");
      Map<String,Object> map = new HashMap<>(8);
      map.put("orderId",this.id);
      map.put("companyId",this.companyId);
      map.put("salesman",this.salesman);
      map.put("orderItems",this.itemList);
      message.setMessages(JSONUtil.toJsonStr(map));
      return JSONUtil.toJsonStr(message);

  }

}


